﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using System.Web.Compilation;
using System.Web;
using System.CodeDom;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace CKS.EBE
{
    [ExpressionEditor(typeof(ResourcesExpressionEditor))]
    public class ResourcesExpressionBuilder : System.Web.Compilation.ExpressionBuilder
    {
        private const string resourcesPrefix = "$Resources:";
        private const string defaultResourceFile = "CKSEBE";

        public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            return ParseExpression(entry.Expression, entry.Type, context);
        }

        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            return null;
        }

        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            // Format : $SPResources:file,key
            string[] parts = expression.Split(',');
            string resKey = null;
            // Default resource file
            string resFile = defaultResourceFile;
            if (parts.Length == 1)
            {
                resKey = parts[0];
            }
            else
            {                
                resFile = parts[0];
                resKey = parts[1];
            }
            // Return translation
            return SPUtility.GetLocalizedString(resourcesPrefix + resKey, resFile, SPContext.Current.Web.Language);
        }

        public override bool SupportsEvaluate
        {
            get
            {
                return true;
            }
        }
    }
}